package com.hnkywl.sts.dao.htdygl;

import com.hnkywl.sts.entity.htgl.Htwb;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-4-17
 * Time: 上午11:46
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class HtwbDao extends SimpleHibernateTemplate<Htwb, Long> {

    public Page<Map> findAllHtmbList(String htmbmc, String htdyId, int pageNo, int pageSize) {

        Page<Map> page = new Page<Map>();
        Map<String, Object> param = new HashMap<String, Object>();
        String conditionSql="";
        String sqlColumn = "select tm.id as \"id\",tm.htmbmc as \"htmbmc\",tm.htdyid as \"htdyid\"," +
                "(select tg.qc from t_sys_gsjg tg where tg.id =tm.jgid) as \"qc\" ," +
                "tm.date_created as \"date_created\",tm.bz as \"bz\",th.mc as \"mc\"  ";
        String sqlBase = " t_biz_htmb tm ,t_biz_htdy th  ";
        if (StringUtils.isNotEmpty(htmbmc)) {
            conditionSql =conditionSql+" and tm.htmbmc like '%"+htmbmc+"%'";
        }

        if (StringUtils.isNotEmpty(htdyId)) {
            conditionSql =conditionSql+" and tm.htdyid="+htdyId;
        }

        String whereSql = "where tm.htdyid = th.id and tm.jgid =" + YgService.getCurrentYgGsId()+ conditionSql;
        String orderSql = " order by tm.date_created desc";
        String countSql = "select count(1) from " + sqlBase + whereSql;
        String resultSql = sqlColumn + " from " + sqlBase + whereSql + orderSql;
        BigDecimal count = (BigDecimal) createSQLQuery(countSql).setProperties(param).uniqueResult();
        page.setTotalCount(count.intValue());
        if (count.intValue() != 0) {
            List<Map> list = createSQLQuery(resultSql)
                    .setProperties(param)
                    .setFirstResult((pageNo - 1) * pageSize)
                    .setMaxResults(pageSize)
                    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                    .list();
            page.setResult(list);
        } else {
            page.setResult(new ArrayList<Map>());
        }
        return page;
    }
}
